// pages/addhomework/addhomework.js
const app = getApp()
const qiniuUploader = require("../../utils/qiniuUploader");
var utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    titlevalue: '',
    contentvalue: '',
    lianjietitlevalue: '',
    lianjiecontentvalue: '',
    checked: false,
    checked1: false,
    minHour: 0,
    maxHour: 23,
    minDate: new Date().getTime(),
    maxDate: new Date(2100, 12, 31).getTime(),
    currentDate: new Date().getTime(),
    shijiashow: false,
    startTimeshijia: null,
    itemList: ["图片", "视频"],
    picList: [],
    lianjiePic: null,
    currentDate1: new Date().getTime(),
    shijiashow1: false,
    startTimeshijia1: null,
    qiniuToken: null,
    photourl: null,
    classid: null,
    fabuflag: false
  },
  selectPic() {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认最多上传9张
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        var tempFilePaths = res.tempFilePaths; // 返回选定照片的本地路径列表 
        that.setData({
          lianjiePic: tempFilePaths
        })
      }

    })
    console.log(that.data.lianjiePic)
  },
  showActionSheet(e) {
    var that = this;
    wx.showActionSheet({
      itemList: this.data.itemList,
      success(e) {
        console.log("success")
        console.log(e)
        if (!e.camcle) {
          if (e.tapIndex == 0) {
            var picList = that.data.picList;
            wx.chooseImage({
              count: 9, // 默认最多上传9张
              sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
              sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
              success(res) {
                console.log(res.tempFilePaths)
                var tempFilePaths = res.tempFilePaths; // 返回选定照片的本地路径列表
                for (var i = 0; i < tempFilePaths.length; i++) {
                  var content = {
                    "url": tempFilePaths[i],
                    "text": "",
                    type: 1,
                    "qiniuurl": ""
                  }
                  picList = picList.concat(content)
                }

                that.setData({
                  picList: picList
                })
              }

            })
            console.log(that.data.picList)
          } else {
            var picList = that.data.picList;
            wx.chooseVideo({
              sourceType: ['album', 'camera'],
              maxDuration: 60,
              camera: 'back',
              success(res) {
                var tempFilePath = res.tempFilePath; // 返回选定照片的本地路径列表 
                var content = {
                  "url": tempFilePath,
                  "text": "",
                  type: 2,
                  "qiniuurl": ""
                }
                that.setData({
                  picList: picList.concat(content)
                })
                console.log(res.tempFilePath)
              }
            })
            console.log(that.data.picList)
          }
          console.log(e.tapIndex)
        } else {
          console.log("cancle")
        }
      },
      fail(e) {
        console.log("fail")
        console.log(e)
      },
      complete(e) {
        console.log("complete")
        console.log(e)
      }
    })
  },
  deletebtnclick: function (e) {
    var index = e.currentTarget.dataset.index;
    console.log("index" + index)
    var picList = this.data.picList;
    picList.splice(index, 1)
    this.setData({
      picList: picList,
    })

  },
  onshihjiaCancel() {
    this.setData({
      shijiashow: false
    });
  },

  showShijJiaPopup() {
    this.setData({
      shijiashow: true
    });
  },

  onshijiaClose() {
    this.setData({
      shijiashow: false
    });
  },
  onshijiaConfirm(event) {
    var timeValue = this.timeFormat(new Date(this.data.currentDate), "yyyy-MM-dd hh:mm");
    this.setData({
      startTimeshijia: timeValue,
      shijiashow: false
    });
  },
  cellClick() {
    var flag = this.data.shijiashow
    flag = !flag
    this.setData({
      shijiashow: flag
    });
  },


  onshihjiaCancel1() {
    this.setData({
      shijiashow1: false
    });
  },

  showShijJiaPopup1() {
    this.setData({
      shijiashow1: true
    });
  },

  onshijiaClose1() {
    this.setData({
      shijiashow1: false
    });
  },
  onshijiaConfirm1(event) {
    var timeValue = this.timeFormat(new Date(this.data.currentDate1), "yyyy-MM-dd hh:mm");
    this.setData({
      startTimeshijia1: timeValue,
      shijiashow1: false
    });
  },
  cellClick1() {
    var flag = this.data.shijiashow1
    flag = !flag
    this.setData({
      shijiashow1: flag
    });
  },


  timeFormat(date, fmt) {
    var o = {
      "M+": date.getMonth() + 1, //月份   
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时   
      "m+": date.getMinutes(), //分   
      "s+": date.getSeconds(), //秒   
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
      "S": date.getMilliseconds() //毫秒   
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;

  },

  onInput(event) {
    console.log(event.detail)
    this.setData({
      currentDate: event.detail,
    });
  },

  onInput1(event) {
    console.log(event.detail)
    this.setData({
      currentDate1: event.detail,
    });
  },

  onChange(event) {
    // wx.showToast({
    //   title: `切换到标签 ${event.detail.name}`,
    //   icon: 'none',
    // });
  },
  onSwitchChange({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    console.log(detail);
    this.setData({
      checked: detail,
      shijiashow: detail
    });
  },
  onSwitchChange1({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    console.log(detail);
    this.setData({
      checked1: detail,
      shijiashow1: detail
    });
  },

  onpictextChange(event) {
    console.log(event);
    var index = event.currentTarget.dataset.index
    console.log("index===" + index);
    var list = this.data.picList
    list[index].text = event.detail;
    this.setData({
      picList: list
    })
  },

  onTitleChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
    this.setData({
      titlevalue: event.detail
    })
  },
  onContentChange(event) {
    console.log(event.detail);
    this.setData({
      contentvalue: event.detail
    })
  },
  onLianjieTitleChange(event) {
    console.log(event.detail);
    this.setData({
      lianjietitlevalue: event.detail
    })
  },
  onLianjieContentChange(event) {
    console.log(event.detail);
    this.setData({
      lianjiecontentvalue: event.detail
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      classid: options.classid
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getQiniuToken()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getQiniuToken: function (e) {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan
    }
    wx.request({
      url: app.globalData.serverQiNiuUrl,
      data: {
        "data": JSON.stringify(data)
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          that.setData({
            qiniuToken: res.data.data.token
          })
        } else {

        }
      },
      fail: function (res) {

      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },

  fabubtnclick: function (e) {

    if (this.data.fabuflag == true) {
      return
    }

    console.log("发作业")
    if (this.data.titlevalue.length == 0) {
      wx.showToast({
        title: "请输入作业主题",
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }
    if (this.data.contentvalue.length == 0) {
      wx.showToast({
        title: "请输入作业内容",
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }


    this.setData({
      photourl: []
    })

    this.setData({
      fabuflag: true
    })

    if (this.data.picList.length > 0) {
      this.sendImge();
    } else {
      var topFlag = 0
      if (this.data.checked) {
        topFlag = 1
      }
      wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
      wx.showLoading({ //显示 loading 提示框
        title: "正在发布...",
      })
      this.postData(topFlag, this.data.startTimeshijia, this.data.titlevalue, this.data.contentvalue, 1)
    }

  },



  postData: function (topFlag, time, title, content, type) {
    var that = this;
    var message = []
    var fengpi;

    for (var i = 0; i < this.data.photourl.length; i++) {
      if (i == 0) {
        fengpi = this.data.photourl[i].url
        if (this.data.photourl[i].type == 2) {
          fengpi = ""
        }
      }
      var attachmentcoverUrl = ""
      if (this.data.photourl[i].type == 2) {
        attachmentcoverUrl = ""
      } else {
        attachmentcoverUrl = this.data.photourl[i].url
      }
      var a = {
        "sType": this.data.photourl[i].type,
        "attachmentID": 0,
        "attachmentUrl": this.data.photourl[i].url,
        "attachmentcoverUrl": attachmentcoverUrl,
        "remark": this.data.photourl[i].text
      }
      message.push(a)
    }

    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "classid": that.data.classid,
      "title": title,
      "content": content,
      "coverPhoto": fengpi,
      "topFlag": topFlag,
      "atlasFlag": 0,
      "topTime": time,
      "contenthomeworkType": type,
      "isSendPhone": 0,
      "sendPhoneContents": "",
      "data": message,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "send_homework"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          wx.showToast({
            title: "发布成功",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          wx.navigateBack({
            url: '../homework/homework'
          })
        } else {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          wx.showToast({
            title: "发布失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          that.setData({
            fabuflag: false
          })
        }
      },
      fail: function (res) {
      
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.showToast({
          title: "发布失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
        that.setData({
          fabuflag: false
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },


  sendImge: function () {
    wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
    wx.showLoading({ //显示 loading 提示框
      title: "正在发布...",
    })

    var pathList = [];
    for (var i = 0; i < this.data.picList.length; i++) {
      var obj = this.data.picList[i]
      var contentObj = {}
      contentObj.url = ""
      contentObj.text = obj.text
      contentObj.type = obj.type
      pathList.push(contentObj)
    }
    this.setData({
      //注意这中间有个"/"在这上面耽误了半个小时
      photourl: pathList
    })

    var count = 0;
    for (var i = 0; i < this.data.picList.length; i++) {

      var timestamp = Date.parse(new Date());
      timestamp = timestamp / 1000;
      var _this = this
      var filepath = ""
      var qiniuurl;
      if (_this.data.picList[i].type == 1) {
        filepath = _this.data.picList[i].url
        qiniuurl = "jygy/" + "photo/" + app.globalData.schoolId + "/" + this.data.classid + "/" + timestamp + "/" + utils.formatDate(new Date()) + utils.wxuuid() + ".jpg"
        _this.data.picList[i].qiniuurl = qiniuurl
      } else {
        filepath = _this.data.picList[i].url
        qiniuurl = "jygy/" + "photo/" + app.globalData.schoolId + "/" + this.data.classid + "/" + timestamp + "/" + utils.formatDate(new Date()) + utils.wxuuid() + ".mp4"
        _this.data.picList[i].qiniuurl = qiniuurl
      }
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
      qiniuUploader.upload(filepath, res => {
        console.log(res)
        var url = res.imageURL
        for (var j = 0; j < _this.data.picList.length; j++) {
          if (_this.data.picList[j].qiniuurl == res.fileName) {
            var pathList1 = _this.data.photourl;
            pathList1[j].url = url
            _this.setData({
              //注意这中间有个"/"在这上面耽误了半个小时
              photourl: pathList1
            })
          }
        }
        count++;
        if (count == _this.data.picList.length) {
          var topFlag = 0
          if (_this.data.checked) {
            topFlag = 1
          }
          _this.postData(topFlag, _this.data.startTimeshijia, _this.data.titlevalue, _this.data.contentvalue, 1)
        }

      }, (error) => {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        _this.setData({
          fabuflag: false
        })
        wx.showToast({
          title: "发布失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
        return;
      }, {
        key: qiniuurl,
        region: 'NCN',
        uptoken: _this.data.qiniuToken,
        uploadURL: 'https://up-z1.qbox.me',
        domain: app.globalData.qiniurUrl,
      })
    }
  },

  fabubtnclick1: function (e) {
    if (this.data.lianjietitlevalue.length == 0) {
      wx.showToast({
        title: "请输入作业主题",
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }
    if (this.data.lianjiecontentvalue.length == 0) {
      wx.showToast({
        title: "请输入作业内容",
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }


    this.setData({
      photourl: []
    })

    this.sendImge1();
  },


  sendImge1: function () {
    var _this = this
    wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
    wx.showLoading({ //显示 loading 提示框
      title: "正在发布...",
    })
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;

    if (_this.data.lianjiePic != null && _this.data.lianjiePic.length > 0) {
      var filepath = _this.data.lianjiePic[0]
      var qiniuurl = "jygy/" + "photo/" + app.globalData.schoolId + "/" + this.data.classid + "/" + timestamp + "/" + utils.formatDate(new Date()) + utils.wxuuid() + ".jpg";
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
      qiniuUploader.upload(filepath, res => {
        console.log(res)
        var url = res.imageURL
        var contentObj = {
          "type": 1,
          "content": "",
          "url": url
        }
        var pathList = _this.data.photourl;
        pathList.push(contentObj)
        _this.setData({
          //注意这中间有个"/"在这上面耽误了半个小时
          photourl: pathList
        })

        var topFlag = 0
        if (_this.data.checked1) {
          topFlag = 1
        }
        _this.postData(topFlag, _this.data.startTimeshijia1, _this.data.lianjietitlevalue, _this.data.lianjiecontentvalue, 2)

      }, (error) => {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.showToast({
          title: "发布失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
        return;
      }, {
        key: qiniuurl,
        region: 'NCN',
        uptoken: _this.data.qiniuToken,
        uploadURL: 'https://up-z1.qbox.me',
        domain: app.globalData.qiniurUrl,
      })
    } else {
      var topFlag = 0
      if (_this.data.checked1) {
        topFlag = 1
      }
      _this.postData(topFlag, _this.data.startTimeshijia1, _this.data.lianjietitlevalue, _this.data.lianjiecontentvalue, 2)
    }

  },

})